package com.example.kotlinproject.net


import android.util.Log
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException
import java.util.concurrent.TimeUnit


/*
* 访问服务器的API接口的客户端
* */
class APIClient {
  var cookies:String? = null

    inner class myInterceptor : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            val request = chain.request()

            val response = chain.proceed(request)
            //response.header("Set-Cookie");
//获取cookie列表
            val headers = response.headers("Set-Cookie")
            for (i in headers.indices) { //这里将cookie储存起来
                Log.d("myInterceptor", "Set-Cookie==" + headers[i])
                if(headers[i].contains("JSESSIONID")){
                    cookies =   headers[i]
                }
            }
            return response
        }
    }


    inner  class AddCookiesInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val builder: Request.Builder = chain.request().newBuilder()
            Log.d("myInterceptor", "AddCookiesInterceptor")
            if(cookies!=null) {
                builder.addHeader("Set-Cookie", cookies)
            }

            return chain.proceed(builder.build())
        }
    }


    //定义单例内Holder
   private object Holder{
        val INSTANCE =APIClient()
    }

    //派生,里面的任何东西都是静态
    companion object{
        val  instance =Holder.INSTANCE
    }


    fun <T> instanceRetrofit(apiInterface:Class<T>):T{
        var okHttpClient = OkHttpClient()
            .newBuilder().
                addInterceptor(myInterceptor()).
                addInterceptor(AddCookiesInterceptor()).
                connectTimeout(1000,TimeUnit.SECONDS)
            .readTimeout(1000,TimeUnit.SECONDS)
            .writeTimeout(1000,TimeUnit.SECONDS)
            .build()
        return Retrofit.Builder().baseUrl("https://www.wanandroid.com").client(okHttpClient).
            addConverterFactory(GsonConverterFactory.create()).
            addCallAdapterFactory(RxJava2CallAdapterFactory.create()).
            build().create(apiInterface)
    }
}